<?php

namespace app\radar\model;

use app\BaseModel;
use app\card\model\UserPhone;
use think\facade\Db;


class RadarCount extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_count';


    protected static function init ()
    {
        //TODO:初始化内容
    }

    /**
     * @Purpose: 雷达列表
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function radarList ( $where = [], $page = 1, $list_rows = 20 )
    {
//        $data = self::where( $where )
//                    ->alias( 'a' )
//                    ->field( [ 'a.*', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import', 'b.gender', 'c.is_auto',
//                                 'c.from_uid', 'c.is_qr', 'c.is_group', 'c.type as c_type', 'c.target_id', 'c.openGId',
//                                 'c.handover_id', 'c.handover_name', 'c.intention','b.is_staff' ]
//                    )
//                    ->join( 'longbing_card_user b', 'a.user_id = b.id' )
//                    ->leftjoin( 'longbing_card_collection c', 'a.user_id = c.uid && a.to_uid = c.to_uid' )
//                    ->order( [ 'a.id' => 'desc' ] )
//                    ->paginate( [ 'list_rows' => $list_rows, 'page' => $page ]
//                    )
//                    ->toArray();



        $data = self::where( $where )
            ->alias( 'a' )
            ->field( [ 'a.*', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import', 'b.gender', 'b.is_staff' ]
            )
            ->join( 'longbing_card_user b', 'a.user_id = b.id' )
            ->order( [ 'a.id' => 'desc' ] )
            ->paginate( [ 'list_rows' => $list_rows, 'page' => $page ]
            )
            ->toArray();





        //耗时 0.02秒
        //  查询手机号
        $tmpArr = [];
        foreach ( $data[ 'data' ] as $index => $item )
        {
            $dis = [

                'user_id'  =>  $item['user_id'],

                'staff_id' =>  $item['to_uid'],
            ];

            $data['data'][$index]['remark_name'] = Db::name('longbing_card_client_info')->where($dis)->value('name');

            $dis = [

                'uid' => $item['user_id'],

                'to_uid'=> $item['to_uid']
            ];

            $collection = Db::name('longbing_card_collection')->where($dis)->find();

            $data['data'][$index]['is_auto']       = !empty($collection['is_auto'])?$collection['is_auto']:0;

            $data['data'][$index]['from_uid']      = !empty($collection['from_uid'])?$collection['from_uid']:0;

            $data['data'][$index]['is_qr']         = !empty($collection['is_qr'])?$collection['is_qr']:0;

            $data['data'][$index]['is_group']      = !empty($collection['is_group'])?$collection['is_group']:0;

            $data['data'][$index]['c_type']        = !empty($collection['type'])?$collection['type']:0;

            $data['data'][$index]['target_id']     = !empty($collection['target_id'])?$collection['target_id']:0;

            $data['data'][$index]['openGId']       = !empty($collection['openGId'])?$collection['openGId']:0;

            $data['data'][$index]['handover_id']   = !empty($collection['handover_id'])?$collection['handover_id']:0;

            $data['data'][$index]['handover_name'] = !empty($collection['handover_name'])?$collection['handover_name']:0;

            $data['data'][$index]['intention']     = !empty($collection['intention'])?$collection['intention']:0;

            $data[ 'data' ][ $index ][ 'phone' ] = '';

            array_push( $tmpArr, $item[ 'user_id' ] );
        }

//        dump($data);exit;
        if ( !empty( $tmpArr ) )
        {
            $tmpArr = array_unique( $tmpArr );


            $list = UserPhone::where( [ [ 'user_id', 'in', $tmpArr ] ] )
                             ->field( [ 'user_id', 'phone' ] )
                             ->select()
                             ->toArray();


            $tmpArr = [];
            foreach ( $list as $index => $item )
            {
                $tmpArr[ $item[ 'user_id' ] ] = $item[ 'phone' ];
            }

            foreach ( $data[ 'data' ] as $index => $item )
            {
                if ( isset( $tmpArr[ $item[ 'user_id' ] ] ) )
                {
                    $data[ 'data' ][ $index ][ 'phone' ] = $tmpArr[ $item[ 'user_id' ] ];
                }
            }
        }


        //By.jingshuixian  2019年12月23日01:51:56
        // 这里很耗时 大概2.0+秒
        if (!empty($data[ 'data' ]))
        {
            //  处理雷达展示日期 耗时 0.03秒
            $data[ 'data' ] = lbHandelRadarDate( $data[ 'data' ] );
            //  处理用户来源  耗时 0.04秒
            $data[ 'data' ] = lbHandelRadarSource( $data[ 'data' ] );
            //  处理雷达激励提醒文案  大概耗时2秒
            $data[ 'data' ] = lbHandelRadarMsg( $data[ 'data' ] );
        }

        return $data;


    }

    /**
     * @Purpose: 员工的递名片数量，浏览数量，靠谱数量
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function RadarNumber ( $userId ,$uniacid)
    {
        $data = [];
        //        //  递名片数量
        //        $shareCount = self::where( [ [ 'to_uid', '=', $userId ], [ 'sign', '=', 'praise' ], [ 'type', '=', '9' ] ]
        //        )
        //                          ->count();
        //  浏览名片数量
        $viewCount = self::where( [ [ 'to_uid', '=', $userId ], ['uniacid' ,'=' ,$uniacid], [ 'sign', '=', 'praise' ], [ 'type', '=', '2' ] ]
        )
                         ->count();
        //  靠谱数量
        $thumbCount = self::where( [ [ 'to_uid', '=', $userId ], ['uniacid' ,'=' ,$uniacid] ,[ 'sign', '=', 'praise' ], [ 'type', '=', '3' ] ]
        )
                          ->count();

        //        $data[] = $shareCount;
        $data[] = intval( $viewCount );
        $data[] = intval( $thumbCount );


        return $data;
    }

    /**
     * @Purpose: 员工未读消息数量
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function unreadNumber ( $userId )
    {
        $number = self::where( [ [ 'to_uid', '=', $userId ], [ 'unread', '=', 1 ] ] )
                      ->count();

        //  把雷达消息变为已读
        self::update( [ 'unread' => 0 ], [ 'to_uid' => $userId ], [ 'unread' ] );

        return $number;
    }

    /**
     * @Purpose: 员工端客户AI分析-客户兴趣占比
     *
     * @Param $client_id 客户id
     * @Param $staff_id 员工id
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function interest ( $client_id, $staff_id, $uniacid )
    {
        $key = 'longbing_user_interest_' . $client_id . '_' . $staff_id;
        $key = md5( $key );

        $value = getCache( $key, $uniacid );

        if ( is_array( $value ) && !empty( $value ) )
        {
            return $value;
        }


        //  对我感兴趣
        $count = self::where( [ [ 'sign', '=', 'copy' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                  [ 'type', 'in', [ 1, 2, 3, 4, 5, 9, 10, 11 ] ] ]
        )
                     ->count();

        $count += self::where( [ [ 'sign', '=', 'praise' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                   [ 'type', 'in', [ 1, 2, 3, 4 ] ] ]
        )
                      ->count();

        $data[] = [ 'data' => $count, 'name' => '对我感兴趣' ];
        $total  = $count;

        //  对产品感兴趣
        $count = self::where( [ [ 'sign', '=', 'copy' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                  [ 'type', '=', 8 ] ]
        )
                     ->count();

        $count += self::where( [ [ 'sign', '=', 'view' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                   [ 'type', 'in', [ 1, 2, 11, 15, 16, 17, 19, 20, 25, 26, 27, 28, 29, 30 ] ] ]
        )
                      ->count();

        $count += self::where( [ [ 'sign', '=', 'praise' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                   [ 'type', 'in', [ 5, 6, 7, 8 ] ] ]
        )
                      ->count();

        $count += self::where( [ [ 'sign', '=', 'order' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ] ]
        )
                      ->count();

        $data[] = [ 'data' => $count, 'name' => '对产品感兴趣' ];
        $total  += $count;

        //  对公司感兴趣
        $count = self::where( [ [ 'sign', '=', 'copy' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                  [ 'type', 'in', [ 6, 7 ] ] ]
        )
                     ->count();

        $count += self::where( [ [ 'sign', '=', 'view' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                   [ 'type', '=', 6 ] ]
        )
                      ->count();

        $data[] = [ 'data' => $count, 'name' => '对公司感兴趣' ];
        $total  += $count;

        foreach ( $data as $index => $item )
        {
            $number                   = $item[ 'data' ];

            if ($total == 0)
            {
                $rate                     = 0;
            }
            else
            {
                $rate                     = $number / $total * 100;
            }

            $rate                     = sprintf( "%.0f", $rate );
            $data[ $index ][ 'rate' ] = $rate;
        }

        @setCache( $key, $data, 1800, $uniacid );

        return $data;
    }

    /**
     * @Purpose: 员工端客户AI分析-近15日客户活跃度
     *
     * @Param $client_id 客户id
     * @Param $staff_id 员工id
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function active ( $client_id, $staff_id, $uniacid )
    {

        $data = [];


        $lastday = date( 'Y/m/d' );

        $number = self::where( [ [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ], [ 'create_time', 'between',
                                   [ strtotime( $lastday . ' 00:00:00' ), strtotime( $lastday . ' 23:59:59' ) ] ] ]
        )
                      ->count();
        $data[] = [ 'date' => date( 'm/d' ), 'number' => $number ];

        $max = $number;

        for ( $i = 1; $i < 15; $i++ )
        {

            $start_time = strtotime( "$lastday -$i days" );

            $md  = date( 'm/d', $start_time );
            $ymd = date( 'Y/m/d', $start_time );

            $end_time = strtotime( $ymd . ' 23:59:59' );

            $number = self::where( [ [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                       [ 'create_time', 'between', [ $start_time, $end_time ] ] ]
            )
                          ->count();

            if ( $number > $max )
            {
                $max = $number;
            }


            $data[] = [ 'date' => $md, 'number' => $number ];
        }

        return [ $data, $max ];
    }

    /**
     * @Purpose: 员工端客户AI分析-客户与我的互动
     *
     * @Param $client_id 客户id
     * @Param $staff_id 员工id
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function interaction ( $client_id, $staff_id, $uniacid )
    {

        $data = [ 'max_number' => 0, 'total' => 0, 'data' => [] ];

        //咨询产品
        $count = self::where( [ [ 'sign', '=', 'copy' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                  [ 'type', '=', 8 ] ]
        )
                     ->count();

        $data[ 'max_number' ] = $count;
        $data[ 'total' ]      += $count;
        $data[ 'data' ][]     = [ 'name' => '咨询产品', 'number' => $count ];

        //  保存电话
        $count = self::where( [ [ 'sign', '=', 'copy' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                  [ 'type', '=', 1 ] ]
        )
                     ->count();

        if ( $count > $data[ 'max_number' ] )
        {
            $data[ 'max_number' ] = $count;
        }
        $data[ 'total' ]  += $count;
        $data[ 'data' ][] = [ 'name' => '保存电话', 'number' => $count ];

        //  拨打电话
        $count = self::where( [ [ 'sign', '=', 'copy' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                  [ 'type', 'in', [ 2, 3, 11 ] ] ]
        )
                     ->count();

        $count += self::where( [ [ 'sign', '=', 'praise' ], [ 'user_id', '=', $client_id ], [ 'to_uid', '=', $staff_id ],
                                   [ 'type', '=', 7 ] ]
        )
                      ->count();

        if ( $count > $data[ 'max_number' ] )
        {
            $data[ 'max_number' ] = $count;
        }
        $data[ 'total' ]  += $count;
        $data[ 'data' ][] = [ 'name' => '拨打电话', 'number' => $count ];



        $view_base_filter = [
            ['user_id', '=', $client_id],
            ['to_uid', '=', $staff_id],
            ['sign', '=', 'view']
        ];

        //浏览商城
        $view_shop_filter = $view_base_filter;
        $view_shop_filter[] = ['type' , '=' , 1];
        $view_shop_number = self::where($view_shop_filter)->count();
        $data['total'] += $view_shop_number;
        $data['data'][] = ['name' => '浏览商城', 'number' => $view_shop_number];


        //浏览商品
        $view_goods_filter = $view_base_filter;
        $view_goods_filter[] = ['type' , '=' , 2];
        $view_goods_number = self::where($view_goods_filter)->count();
        $data['total'] += $view_goods_number;
        $data['data'][] = ['name' => '浏览商品', 'number' => $view_goods_number];

        //查看官网
        $view_official_web_filter = $view_base_filter;
        $view_official_web_filter[] = ['type' , '=' , 6];
        $view_official_web_number = self::where($view_official_web_filter)->count();
        $data['total'] += $view_official_web_number;
        //菜单名字
        $name = tabbarName(4,$uniacid);
        $data['data'][] = ['name' =>!empty($name)?'查看'.$name :'查看官网', 'number' => $view_official_web_number];


        //浏览动态
        $view_timeline_filter = $view_base_filter;
        $view_timeline_filter[] = ['type' , '=' , 3];
        $view_timeline_number = self::where($view_timeline_filter)->count();
        $data['total'] += $view_timeline_number;
        $data['data'][] = ['name' => '浏览动态', 'number' => $view_timeline_number];


        //点赞
        $praise_filter = [
            ['user_id', '=', $client_id],
            ['to_uid', '=', $staff_id],
            ['sign', '=', 'praise'],
            ['type', 'IN', [1, 3]]
        ];
        $praise_number = self::where($praise_filter)->count();
        $data['total'] += $praise_number;
        $data['data'][] = ['name' => '点赞', 'number' => $praise_number];



        //分享名片
        $share_filter = [
            ['user_id', '=', $client_id],
            ['to_uid', '=', $staff_id],
            ['sign', '=', 'praise'],
            ['type', '=', 4]
        ];
        $share_number = self::where($share_filter)->count();
        $data['total'] += $share_number;
        $data['data'][] = ['name' => '分享', 'number' => $share_number];




        //按number倒序
        $sort_arr = [];
        foreach ($data['data'] as $k => $v) {
            $sort_arr[] = $v['number'];
        }

        array_multisort($sort_arr, SORT_DESC, $data['data']);
        $data['max_number'] = $data['data'][0]['number'] ?? 0;

        //计算rate
        foreach ($data['data'] as $index => $item) {
            if ($data['max_number'] == 0) {
                $rate = 0;
            } else {
                $rate = $item['number'] / $data['max_number'] * 100;
            }
            $rate = sprintf("%.0f", $rate);
            $data['data'][$index]['rate'] = $rate;
        }

        return $data;
    }

    /**
     * @Purpose: 名片最近浏览情况
     *
     * @Param $staff_id 员工id
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    public function getCardViewInfo ( $staff_id, $uniacid )
    {
        $where   = array( [ 'a.to_uid', '=', $staff_id ], [ 'b.avatarUrl', '<>', '' ], [ 'a.user_id', '<>', $staff_id ] );
        $dataSql = self::where( $where )
                       ->alias( 'a' )
                       ->field( [ 'a.id as count_id', 'a.user_id', 'b.nickName', 'b.avatarUrl', 'b.avatarUrl', 'b.import',
                                    'b.gender' ]
                       )
                       ->join( 'longbing_card_user b', 'a.user_id = b.id' )
                       ->order( [ 'a.id' => 'desc' ] )
                       ->buildSql();

        $data = Db::table( $dataSql . ' a' )
                  ->group( 'a.user_id' )
                  ->order( 'count_id desc')
                  ->limit( 5 )
                  ->select();

        $count = self::where( [ [ 'to_uid', '=', $staff_id ] ] )
                     ->group( 'user_id' )
                     ->count();

        return [ $data, $count ];
    }
    public function getShareNumber($staff_id)
    {
//      $count = $this->whereOr([
//                               [['sign' , '=' , 'praise']  ,['type' , '=' , 4] ,['user_id' , '=' , $staff_id] ,['to_uid' , '=' , 0]] ,
//                               [['sign' , '=' , 'praise'] ,['type', '=' , 4] ,['user_id' , '=' , $staff_id] ,['to_uid' , '=' , $staff_id]] ,
//                               [['sign' , '=' , 'copy'] ,['type' , '=' , 10] ,['user_id' , '=' , $staff_id] ,['to_uid' , '=' , 0 ]] ,
//                               [['sign' , '=' , 'copy'] ,['type' , '=' , 10] ,['user_id' , '=' , $staff_id] ,['to_uid' , '=' , $staff_id]]
//                              ])->count();
        $count = $this->whereOr([
                                 [['sign' , '=' , 'praise']  ,['type' , '=' , 4] ,['user_id' , '=' , $staff_id] ] ,
                                 [['sign' , '=' , 'copy'] ,['type' , '=' , 10] ,['user_id' , '=' , $staff_id]]
                                ])->count();
        return $count;
    }
    
    public function createCount($data)
    {
        $data['create_time'] = time();
        $result = $this->save($data);
        return !empty($result);
    }


    /**
     * @param $staff_id
     * @功能说明:新的递名片数量
     * @author chenniang
     * @DataTime: 2020-04-01 09:28
     */

    public function getShareNumberV2($staff_id)
    {
        $count = $this->whereOr([
            [['sign' , '=' , 'praise']  ,['type' , '=' , 4] ,['to_uid' , '=' , $staff_id] ] ,
            [['sign' , '=' , 'copy'] ,['type' , '=' , 10] ,['to_uid' , '=' , $staff_id]],
            [['sign' , '=' , 'copy'] ,['type' , '=' , 10] ,['user_id' , '=' , $staff_id] ,['to_uid' , '=' , 0 ]] ,
            [['sign' , '=' , 'praise']  ,['type' , '=' , 4] ,['user_id' , '=' , $staff_id] ,['to_uid' , '=' , 0]] ,
        ])->count();
        return $count;
    }
}